package com.gengzp.mq.server.exception;

import com.gengzp.mq.common.model.base.MqResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

/**
 * @ClassName GengzpMqExceptionHandler
 * @Description 消息队列框架全局异常捕获类
 * @Author gengzp
 * @Date 2025/6/8 14:12
 */
@RestControllerAdvice
public class GengzpMqExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GengzpMqExceptionHandler.class);

    /**
     * 处理其他不可控异常（处理其他的 Exception）
     */
    @ResponseBody
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public MqResult<?> handleException(Exception e) {
        logger.error("出现系统异常，详细信息: ", e);
        return MqResult.getFailResult(e.getCause().getMessage());
    }

    /**
     * 运行时异常
     */
    @ResponseBody
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public MqResult<?> handleRuntimeException(RuntimeException e) {
        logger.error("出现运行时异常，详细信息: ", e);
        return MqResult.getFailResult(e.getMessage());
    }

    /**
     * 处理参数校验异常（处理 @Valid 注解参数校验不通过）
     */
    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public MqResult<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        String errorMessage = e.getBindingResult().getFieldErrors().stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.joining(";\n"));
        logger.error("出现参数校验异常，详细信息: ", e);
        return MqResult.getFailResult(errorMessage);
    }

}
